package com.itheima.app.manager;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSON;
import com.itheima.app.interceptor.UserHolder;
import com.itheima.autoconfig.huanxin.HuanXinTemplate;
import com.itheima.domain.db.Question;
import com.itheima.domain.db.UserInfo;
import com.itheima.domain.mongo.Comment;
import com.itheima.domain.mongo.Friend;
import com.itheima.domain.vo.ContactVo;
import com.itheima.domain.vo.PageBeanVo;
import com.itheima.domain.vo.UserCommentVo;
import com.itheima.service.db.QuestionService;
import com.itheima.service.db.UserInfoService;
import com.itheima.service.mongo.CommentService;
import com.itheima.service.mongo.FriendService;
import jdk.management.resource.internal.inst.UnixAsynchronousServerSocketChannelImplRMHooks;
import org.apache.commons.collections.map.HashedMap;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class MessageManager {

    @Autowired
    private HuanXinTemplate huanXinTemplate;

    @Reference
    private UserInfoService userInfoService;

    @Reference
    private QuestionService questionService;

    @Reference
    private FriendService friendService;

    @Reference
    private CommentService commentService;

    // 聊一下（向陌生人发送一条消息）
    public ResponseEntity sendStrangerQuestions(String jiarenId, String reply) {
        // 1.获取登录人用户id
        Long userId = UserHolder.get().getId();
        // 2.查询登录用户昵称
        String nickname = userInfoService.findById(userId).getNickname();
        // 3.查询陌生人问题
        Question question = questionService.findByUserId(Long.valueOf(jiarenId));
        if (question == null) {
            question = new Question();
            question.setStrangerQuestion("你是喜欢GG还是MM？");
        }

        // 4.组装发送条件
        Map<String, String> requestBody = new HashedMap();
        requestBody.put("userId", userId.toString());
        requestBody.put("nickname", nickname);
        requestBody.put("strangerQuestion", question.getStrangerQuestion());
        requestBody.put("reply", reply);

        String json = JSON.toJSONString(requestBody);
        // 5.调用环信发送消息
        huanXinTemplate.sendMsg(jiarenId, json);
        return ResponseEntity.ok(null);
    }

    // 聊一下（添加好友）
    public ResponseEntity addContacts(Long friendId) {
        // 1.获取登录用户id（我的）
        Long userId = UserHolder.get().getId();
        // 2.向mongoDB建立好友关系
        friendService.addContact(userId, friendId);
        // 3.向环信建立好友关系
        huanXinTemplate.addContacts(userId, friendId);
        return ResponseEntity.ok(null);
    }

    public ResponseEntity findContacts(Integer pageNum, Integer pageSize) {
        // 1.获取登录用户id
        Long userId = UserHolder.get().getId();
        // 2.调用rpc查询
        PageBeanVo pageBeanVo = friendService.findContactByPage(pageNum, pageSize, userId);

        // 3.封装vo
        List<ContactVo> voList = new ArrayList<>();
        List<Friend> friendList = (List<Friend>) pageBeanVo.getItems();
        if (CollectionUtil.isNotEmpty(friendList)) {
            for (Friend friend : friendList) {
                // 好友id
                Long friendId = friend.getFriendId();

                // 查询好友信息
                UserInfo userInfo = userInfoService.findById(friendId);

                // 封装vo
                ContactVo contactVo = new ContactVo();
                contactVo.setUserInfo(userInfo); // 好友信息
                contactVo.setUserId(friendId.toString()); // 好友id

                voList.add(contactVo);
            }
        }

        // 4.返回结果
        pageBeanVo.setItems(voList);
        return ResponseEntity.ok(pageBeanVo);
    }

    public ResponseEntity findComment(Integer pageNum, Integer pageSize, Integer commentType) {
        // 1.获取登录用户id
        Long userId = UserHolder.get().getId();
        // 2.调用rpc查询
        PageBeanVo pageBeanVo = commentService.findCommentByPage(pageNum, pageSize, userId, commentType);
        // 3.封装vo
        List<UserCommentVo> voList = new ArrayList<>();
        List<Comment> commentList = (List<Comment>) pageBeanVo.getItems();
        if (CollectionUtil.isNotEmpty(commentList)) {
            for (Comment comment : commentList) {
                // 获取评论人id
                Long commentUserId = comment.getUserId();

                // 查询评论人信息
                UserInfo userInfo = userInfoService.findById(commentUserId);

                // 创建vo
                UserCommentVo userCommentVo = new UserCommentVo();
                userCommentVo.setId(commentUserId.toString()); // 评论人id
                userCommentVo.setAvatar(userInfo.getAvatar()); // 评论人头像
                userCommentVo.setNickname(userInfo.getNickname()); // 评论人昵称
                userCommentVo.setCreateDate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(comment.getCreated())));

                // 设置到volist
                voList.add(userCommentVo);
            }
        }

        // 4.返回结果
        pageBeanVo.setItems(voList);
        return ResponseEntity.ok(pageBeanVo);
    }
}
